<template>
    <div class="container">
        <!-- 头部 -->
        <el-row>
            <div class="row_Left">
                <div class="line"></div>
                <div class="title">用户管理</div>
                <el-input
                    placeholder="请输入姓名"
                    v-model="search"
                    class="seachName"
                >
                </el-input>
                <el-button type="primary" class="search" @click="goSearchUser">
                    <el-icon style="margin-right:5px"><Search /></el-icon>
                    搜索
                </el-button>
            </div>
            <div class="row_Right">
                <el-button type="primary" link class="reCycle" @click="goCycleBin" v-if="showCycleBin == false">回收站</el-button>
                <el-button type="primary" link class="addBtn" @click="goAddUser" v-if="showCycleBin == false">
                    <img src="../../assets/images/加号.png" alt="">
                </el-button>
                <el-button type="danger" link class="delBtn" @click="goDeleteUserAll" v-if="showCycleBin == false">
                    <img src="../../assets/images/删除.png" alt="">
                </el-button>
                <el-button  type="primary" link class="reCycle" v-if="showCycleBin == true" @click="goRestoreUserAll">还原</el-button>
                <el-button type="primary" link class="addBtn" v-if="showCycleBin == true" @click="showCycleBin = false;search = ''">
                    <img src="../../assets/images/back.png" alt="">
                </el-button>
            </div>
        </el-row>
        <!-- 底部 -->
        <div class="content">
            <!-- 用户列表表格 -->
            <el-table :data="userList" @select="selectCheckDel" @select-all="selectCheckDelAll" v-if="showCycleBin == false">
                <el-table-column type="selection"></el-table-column>
                <el-table-column label="姓名" prop="userName"></el-table-column>
                <el-table-column label="部门" prop="department"></el-table-column>
                <el-table-column label="性别" prop="sex"></el-table-column>
                <el-table-column label="电话" prop="tel"></el-table-column>
                <el-table-column prop="roleName">
                    <template #header>
                        <el-select
                            placeholder="全部职能"
                            v-model="roleId"
                            clearable
                            @change="changeFun"
                        >
                        <el-option
                            :key="0"
                            label="全部职能"
                            :value="0"
                        ></el-option>
                        <el-option
                            v-for="item in role1"
                            :key="item.roleId"
                            :value="item.roleId"
                            :label="item.roleName"
                        ></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scoped">
                        <el-button type="success" link @click="goModifyUser(scoped.row.userId)">修改</el-button>
                        <el-button type="primary" link @click="goResetPassword(scoped.row.userId)">重置</el-button>
                        <el-button type="danger" link @click="goDeleteUser(scoped.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 用户列表分页器 -->
            <div class="myPage" v-if="showCycleBin == false">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="total"
                    :current-page="pageIndex"
                    :page-size="pageSize"
                    @current-change="handleCurrentChange"
                />
                每页
                <el-input-number
                    v-model="pageSize"
                    :min="1"
                    controls-position="right"
                    size="large"
                    @change="handleChange"
                />
                条
            </div>
            <!-- 回收站用户列表表格 -->
            <el-table :data="cycleBinList" v-if="showCycleBin == true" @select="selectCheckRestore" @select-all="selectCheckRestoreAll">
                <el-table-column type="selection"></el-table-column>
                <el-table-column label="姓名" prop="userName"></el-table-column>
                <el-table-column label="部门" prop="department"></el-table-column>
                <el-table-column label="性别" prop="sex"></el-table-column>
                <el-table-column label="电话" prop="tel"></el-table-column>
                <el-table-column prop="roleName">
                    <template #header>
                        <el-select
                            placeholder="全部职能"
                            v-model="roleId"
                            clearable
                            @change="changeFun"
                        >
                        <el-option
                            :key="0"
                            label="全部职能"
                            :value="0"
                        ></el-option>
                        <el-option
                            v-for="item in role1"
                            :key="item.roleId"
                            :value="item.roleId"
                            :label="item.roleName"
                        ></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scoped">
                        <el-button type="success" link @click="goRestoreUser(scoped.row)">还原</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 回收站用户列表分页器 -->
            <div class="myPage" v-if="showCycleBin == true">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="total1"
                    :current-page="pageIndex"
                    :page-size="pageSize"
                    @current-change="handleCurrentChange"
                />
                每页
                <el-input-number
                    v-model="pageSize"
                    :min="1"
                    controls-position="right"
                    size="large"
                    @change="handleChange"
                />
                条
            </div>
        </div>
        <!-- 添加模态框 -->
        <el-dialog v-model="userDialogValue" title='添加用户' :show-close="false">
            <div class="form">
                <el-form :model="addUserData" :rules="rules" ref="myForm">
                    <div class="formRow">
                        <el-form-item label="姓名" prop="userName">
                            <el-input v-model="addUserData.userName" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="部门" prop="department">
                            <el-select v-model="addUserData.department" placeholder="请选择部门">
                                <el-option
                                    v-for="item in departmentList"
                                    :key="item.departmentId"
                                    :value="item.departmentName"
                                    :label="item.departmentName"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="formRow">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="addUserData.sex" placeholder="请选择性别">
                                <el-option value="男">男</el-option>
                                <el-option value="女">女</el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="职能" prop="roleId">
                            <el-select v-model="addUserData.roleId" placeholder="请选择职能">
                                <el-option
                                    v-for="item in role"
                                    :key="item.roleId"
                                    :value="item.roleId"
                                    :label="item.roleName"
                                    :disabled="item.roleId == 1 || item.roleId == 4"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="formRow">
                        <el-form-item label="账号" prop="account">
                            <el-input v-model="addUserData.account" placeholder="请输入账号"></el-input>
                        </el-form-item>
                        <el-form-item label="电话" prop="tel">
                            <el-input v-model="addUserData.tel" placeholder="请输入电话"></el-input>
                        </el-form-item>
                    </div>
                    <div class="formRow">
                        <el-form-item label="密码">
                            <el-input v-model="addUserData.password"></el-input>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <footer class="footerDialog">
                <el-button @click="userDialogValue = false">取消</el-button>
                <el-button @click="goSureAddUser(myForm)">确定</el-button>
            </footer>
        </el-dialog>
        <!-- 编辑模态框 -->
         <el-dialog v-model="userModifyDialogValue" title='修改用户' :show-close="false">
            <div class="form">
                <el-form :model="addUserData" :rules="rules" ref="myForm">
                    <div class="formRow">
                        <el-form-item label="姓名" prop="userName">
                            <el-input v-model="addUserData.userName" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="部门" prop="department">
                            <el-select v-model="addUserData.department" placeholder="请选择部门">
                                <el-option
                                    v-for="item in departmentList"
                                    :key="item.departmentId"
                                    :value="item.departmentName"
                                    :label="item.departmentName"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="formRow">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="addUserData.sex" placeholder="请选择性别">
                                <el-option value="男">男</el-option>
                                <el-option value="女">女</el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="职能" prop="roleId">
                            <el-select v-model="addUserData.roleId" placeholder="请选择职能">
                                <el-option
                                    v-for="item in role"
                                    :key="item.roleId"
                                    :value="item.roleId"
                                    :label="item.roleName"
                                    :disabled="item.roleId == 1 || item.roleId == 4"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="formRow">
                        <el-form-item label="账号">
                            <el-input v-model="addUserData.account" placeholder="请输入账号" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="电话" prop="tel">
                            <el-input v-model="addUserData.tel" placeholder="请输入电话"></el-input>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <footer class="footerDialog">
                <el-button @click="userModifyDialogValue = false">取消</el-button>
                <el-button @click="goSureAddUser(myForm)">确定</el-button>
            </footer>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref ,reactive} from 'vue';
import '../../assets/header.css'
import { getUserList,getRoleList,getDepartmentList,addUser,queryUserNews,ModifyUser,deleteUser,cycleBinUser,restoreUser } from '../api/User';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
let userList = ref([])//用户列表
let pageIndex = ref(1)//当前页码
let pageSize = ref(7)//每页条数
let search = ref("")//根据姓名搜索
let roleId = ref()//根据用户职能搜索 查全部传 0
let role = ref([])//职能
let role1 = ref([])//职能不包括超级管理员
let total = ref(0)//总共的数据数量
//调取用户列表的接口
let userListFun = () => {
    let userListData = reactive({
        pageIndex:pageIndex.value,
        pageSize:pageSize.value,
        search:search.value,
        roleId:roleId.value,
    })
    getUserList('userList', userListData)
    .then((res) => {
    if (res.code === 200) {
        userList.value = res.dataset.userList
        total.value = res.dataset.pageCount * pageSize.value
        // console.log(userList.value);
    }
  })
}
//模态框
let userFlag = ref(0)//0：添加用户 1：修改用户
let userDialogValue = ref(false)//模态框开关(增加)
let userModifyDialogValue = ref(false)//模态框开关(修改)
let myForm = ref("")
let addUserData = reactive({
    userName:"",//用户姓名
    department:"",//部门
    sex:"",//性别
    tel:"",//电话
    roleId:"",//职能
    account:"",//账号
    password:"123456",//密码
})
//点击添加用户
let goAddUser = () => {
    userDialogValue.value = true
    userFlag.value = 0
    addUserData = reactive({
        userName:"",//用户姓名
        department:"",//部门
        sex:"",//性别
        tel:"",//电话
        roleId:"",//职能
        account:"",//账号
        password:"123456",//密码
    })
}
//点击修改用户
let userId2 = ref("")
let goModifyUser = userId => {
    userModifyDialogValue.value = true
    userFlag.value = 1
    userId2.value = userId
    queryUserNewsFun(userId)
}
//点击修改用户后根据成员 Id 查询信息
let queryUserNewsFun = userId => {
    if(userFlag.value = 1){
        let queryUserNewsData = { userId:userId }
        queryUserNews('userById',queryUserNewsData)
        .then(res => {
            if(res.code == 200){
                // console.log(res);
                addUserData.userName = res.dataset.userName
                addUserData.department = res.dataset.department
                addUserData.sex = res.dataset.sex
                addUserData.tel = res.dataset.tel
                addUserData.roleId = res.dataset.roleId
                addUserData.account = res.dataset.account
            }
        })
    }
}
//表单验证规则
let rules = reactive({
    userName:[{required:true,message:"请输入姓名",trigger:'blur'}],
    department:[{required:true,message:"请选择部门",trigger:'change'}],
    sex:[{required:true,message:"请选择性别",trigger:'change'}],
    tel:[{required:true,message:"请输入电话",trigger:'blur'},
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入有效的 11 位电话号码',
            trigger: 'blur',
        }
    ],
    roleId:[{required:true,message:'请选择职能',trigger:'change'}],
    account:[{required:true,message:'请输入账号',trigger:'blur'}],
})
//点击确定，进行添加用户/修改用户
let goSureAddUser = (formEl) => {
    formEl.validate(valid => {
        if(valid && userFlag.value == 0){//添加用户
            addUser('addUser',addUserData)
            .then(res => {
                if(res.code == 200){
                    ElMessage.success('添加成功')
                    userDialogValue.value = false
                    userListFun()
                }else{
                    ElMessage.info('手机号或账号已存在')
                }
            })
        }else if(valid && userFlag.value == 1){//修改用户
            addUserData.userId = userId2.value
            ModifyUser('updateUser',addUserData)
            .then(res => {
                if(res.code == 200){
                    ElMessage.success('修改成功')
                    userModifyDialogValue.value = false
                    userListFun()
                }else{
                    ElMessage.info(res.msg)
                }
            })
        }
    })
}
//点击单行的删除
let goDeleteUser = row => {
    ElMessageBox.confirm(
    '确定要删除行吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      //选择确认删除调删除接口
      const userIds = [row.userId]
      deleteUser('deleteUser',{ userIds: userIds })
      .then(res => {
        if(res.code == 200){
            // console.log(res);
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            userListFun()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}
let deleteArr = ref([])//要删除用户的用户Id的数组
//每行数据的复选框发生改变(删除)
let selectCheckDel = (row) => {
    // console.log(row);//选中行的数据
    deleteArr.value = row.map(item => item.userId)
}
//点击全选的复选框(删除)
let selectCheckDelAll = (row) => {
    deleteArr.value = row.map(item => item.userId)
}
//点击多行删除
let goDeleteUserAll = () => {
    // console.log(deleteArr.value);
    if(deleteArr.value.length == 0){
        ElMessage.warning('请先勾选要删除的行')
    }else{
        ElMessageBox.confirm(
            '确定要删除选中的行吗?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(() => {
            deleteUser('deleteUser',{ userIds: deleteArr.value })
            .then(res => {
                if(res.code == 200){
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    userListFun()
                }
            })
            deleteArr.value = []
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
    }
}
//点击重置密码
let goResetPassword = (userId) => {
    // console.log(userId);
    ElMessageBox.confirm(
        '确认要将密码重置为123456吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(() => {
        let queryUserNewsData = { userId:userId }
        queryUserNews('userById',queryUserNewsData)
        .then(res => {
            if(res.code == 200){
                // console.log(res);
                addUserData.userName = res.dataset.userName
                addUserData.department = res.dataset.department
                addUserData.sex = res.dataset.sex
                addUserData.tel = res.dataset.tel
                addUserData.roleId = res.dataset.roleId
                addUserData.account = res.dataset.account
            }
            addUserData.password = '123456'
            addUserData.userId = userId
            ModifyUser('updateUser',addUserData)
            .then(res => {
                if(res.code == 200){
                    ElMessage({
                        type: 'success',
                        message: '重置成功',
                    })
                }
            })
        })
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消重置',
        })
    })
}
//点击前往回收站
let showCycleBin = ref(false)//判断是否显示回收站
let cycleBinList = ref([])//回收站数据列表
let total1 = ref(0)//总条数
//点击前往回收站---点击回收站时调取回收站数据的接口
let goCycleBin = () => {
    showCycleBin.value = true
    search.value = ""
    cycleBinListFun()
}
//调取回收站数据
let cycleBinListFun = () => {
    let cycleBinData = reactive({
        pageIndex:pageIndex.value,
        pageSize:pageSize.value,
        userName:search.value,
        roleId:roleId.value,
    })
    cycleBinUser('recycleBinList',cycleBinData)
    .then(res => {
        if(res.code == 200){
            // console.log(res);
            cycleBinList.value = res.dataset.recycleBinList
            total1.value = res.dataset.pageCount * pageSize.value
        }
    })
}
//点击单行的还原用户
let goRestoreUser = (row) => {
    // console.log(row);
    const userId = [row.userId]
    ElMessageBox.confirm(
        '确认要还原行吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(() => {
        restoreUser('updateDelFlag',userId)
        .then(res => {
            if(res.code == 200){
                ElMessage({
                    type: 'success',
                    message: '还原成功',
                })
                cycleBinListFun()
                userListFun()
            }
        })  
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消还原',
        })
    })
}
//每行数据的复选框发生改变时(还原)
let restoreArr = ref([])//要还原用户的数组
let selectCheckRestore = (row) => {
    restoreArr.value = row.map(item => item.userId)
}
//点击全选的复选框(还原)
let selectCheckRestoreAll = (row) => {
    restoreArr.value = row.map(item => item.userId)
}
//点击多行还原
let goRestoreUserAll = () => {
    if(restoreArr.value.length == 0){
        ElMessage.warning('请先勾选要还原的行')
    }else{
        ElMessageBox.confirm(
            '确定要还原选中的用户嘛?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(() => {
            restoreUser('updateDelFlag',restoreArr.value)
            .then(res => {
                if(res.code == 200){
                    ElMessage({
                        type: 'success',
                        message: '还原成功',
                    })
                    cycleBinListFun()
                    userListFun()
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消还原',
            })
        })
    }
}
//调取角色列表接口
let roleListFun = () => {
    let roleData = {}
    getRoleList('roleList',roleData)
    .then(res => {
        if(res.code == 200){
            role.value = res.dataset
            role1.value = res.dataset.filter(item => item.roleId != 1)
        }
    })
}
//选择职能时，调取接口
let changeFun = (v) => {
    roleId.value = v
    if(!showCycleBin.value){
        userListFun()
    }else{
        cycleBinListFun()
    }
}
//点击搜索调取接口
let goSearchUser = () => {
    if(!showCycleBin.value){
        userListFun()
    }else{
        console.log(search.value);
        cycleBinListFun()
    }
}
//分页器的页码发生改变时
const handleCurrentChange = (val) => {
  pageIndex.value = val;
  if(!showCycleBin.value){
    userListFun()
  }else{
    cycleBinListFun()
  }
}
//分页器的每页数据条数发生改变时
const handleChange = (value) => {
  pageSize.value = value
  if(!showCycleBin.value){
    userListFun()
  }else{
    cycleBinListFun()
  }
}
//部门列表
let departmentList = ref([])
let departmentListFun = () => {
    let departmentData = {}
    getDepartmentList('departmentList',departmentData)
    .then(res => {
        if(res.code == 200){
            departmentList.value = res.dataset.departmentList
        }
    })
}
//页面加载，调取用户接口与职能接口
onMounted(() => {
    userListFun()
    roleListFun()
    departmentListFun()
})
</script>

<style lang="less" scoped>

</style>